package com.hutiao.snowhb.interceptor;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.hutiao.snowhb.entities.AnalyticsLog;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LogInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 7037983567991990268L;
	
	private static Logger logger = Logger.getLogger(LogInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		
		Timestamp requestTime = new Timestamp(System.currentTimeMillis());
		ActionContext ctx = invocation.getInvocationContext();
		
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
		logger.debug("RequestURI:" + request.getRequestURI());
		
		// 执行下面的拦截器
		String result = invocation.invoke();
		
		
		// 记录日志
		AnalyticsLog anaLog = new AnalyticsLog();
		anaLog.setRequestTime(requestTime);
		anaLog.setUri(request.getRequestURI());
		anaLog.setParam(request.getQueryString());
		anaLog.setReferer(request.getHeader("referer"));
		anaLog.setResponseTime(new Timestamp(System.currentTimeMillis()));
		anaLog.setResult(result);
		anaLog.setUserAgent(request.getHeader("User-Agent"));
		anaLog.writeLog();
		
		return Action.SUCCESS;
	}

}
